package com.tb.ClassSchedule;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

/**
 * Created by guich on 2016/8/4.
 */
public class Test extends AppCompatActivity {

    public String num = "1410421059";
    public String psw = "1996@0722";
    public String rdc = null;
    public String cookieVal = null;

    //第一个URL，等着为后面服务
    public static final String login_url  = "https://passport.csdn.net";
    //第一个Post模拟登陆的URL
    public static final String login_url2 = "https://passport.csdn.net/account/login?from=http%3A%2F%2Fmy.csdn.net%2Fmy%2Fmycsdn";


    private TextView  text;
    private ImageView imageView;
    private Bitmap    img;
    private EditText  editText;
    private Button    button;

    private static final int     TIME_LIMIT = 8000;    //设置超时时间
    private              Handler handler    = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    text.setText("sorry，连接失败，请查看网络是否通畅。。。");
                    break;
                case 1:
                    text.setText(msg.obj.toString());
                    break;
                case 2:
                    imageView.setImageBitmap(img);

            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);
        text = (TextView) findViewById(R.id.text);
        imageView = (ImageView) findViewById(R.id.img);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                text.setText("源码拼命加载中。。。");

                rdc = String.valueOf(editText.getText());
                Log.d("tb",rdc);

                sendHttpURLConnection();
//              sendHttpClient();


            }
        });
       getRandomCode();


    }

    private void getRandomCode(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                URL      url = null;
                try {
                    url = new URL("http://jwxt.hfnu.edu.cn/(y3qr5j55pyeaf045siyih345)/CheckCode.aspx");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    InputStream is = connection.getInputStream();
                    img = BitmapFactory.decodeStream(is);
                    // 取得cookie，相当于记录了身份，供下次访问时使用
                    cookieVal = connection.getHeaderField("Set-Cookie");
                    Log.d("tb",cookieVal);
                    is.close();

                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        };
        new Thread(runnable).start();


    }

    private void sendHttpURLConnection() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;

                try {



                    String surl = "http://jwxt.hfnu.edu.cn/(y3qr5j55pyeaf045siyih345)/default2.aspx";

                    /**
                     * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。比如： // Using
                     * java.net.URL and //java.net.URLConnection
                     */




                    URL url        = new URL(surl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    /**
                     * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。
                     * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做：
                     */
                    connection.setDoOutput(true);
                    connection.setRequestProperty("Cookie",cookieVal);
                    connection.connect();
                    /**
                     * 最后，为了得到OutputStream，简单起见，把它约束在Writer并且放入POST信息中，例如： ...
                     */

                    OutputStreamWriter out = new OutputStreamWriter(connection
                            .getOutputStream(), "gb2312");
                    //其中的memberName和password也是阅读html代码得知的，即为表单中对应的参数名称
                    out.write("__VIEWSTATE=dDwyODE2NTM0OTg7Oz4J1M0E12oUlEr84Lqk6/XAPSioRg==" +
                            "&txtUserName=" + num +
                            "&TextBox2=" + psw +
                            "&txtSecretCode=" + rdc +
                            "&RadioButtonList1=学生"); // post的关键所在！
//                    cookieVal = connection.getHeaderField("Set-Cookie");
//                    Log.d("tb", "" + cookieVal);

                    // remember to clean up
                    out.flush();
                    out.close();


//                    // 取得cookie，相当于记录了身份，供下次访问时使用
//                    String cookieVal = connection.getHeaderField("Set-Cookie");
//                    Log.d("tb",connection.getResponseCode() + "\n" + cookieVal);



















                    String path = "http://jwxt.hfnu.edu.cn/(y3qr5j55pyeaf045siyih345)/xs_main.aspx?xh=1410421059";
                    url  = new URL(path);


                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
////
//                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//                    out.writeBytes("username=18326143595&password=1996@0722");

//                    connection.setRequestProperty("Accept-Charset","gb2312");
//                    connection.setRequestProperty("Content-Type","text/html;gb2312");
//                    connection.setRequestProperty("Cookie","UserName=ThronBirds; UserInfo=3Q5gr9gij%2Flfx6OCL%2BkgRt8%2FhekUFbUnUpNdI9dXFbgyvagmtBv%2B2OBLpEc0bSJf1BznNdm1cGzGsAup%2FLoRSpcWn8ytBfoBcEaEpI%2FGWbM%3D; UserNick=ThronBirds; AU=C82; UN=ThronBirds; UE=\"\"; BT=1470367808009; access-token=3b736bd5-87e9-40ef-a4d6-46971f5d748c");
                    connection.setRequestProperty("Cookie",cookieVal);

                    connection.connect();

                    InputStream urlStream = connection.getInputStream();

                    BufferedReader bufferedReader = new BufferedReader(

                            new InputStreamReader(urlStream, Charset.forName("gb2312")));

                    String ss = null;
                    StringBuilder total = new StringBuilder();
                    while ((ss = bufferedReader.readLine()) != null) {
                        total.append(ss);
                    }
                    bufferedReader.close();
                    connection.disconnect();

//      System.out.println(total.toString());










                    Message message = new Message();
                    message.what = 1;
                    message.obj = total.toString();
                    handler.sendMessage(message);

                } catch (SocketTimeoutException | UnknownHostException e) {
                    //连接主机超时
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        };
        new Thread(runnable).start();
    }


    private void sendHttpClient() {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String cookie = null, location = null;
                HttpClient client = new DefaultHttpClient();
/*
                HttpPost httpPost = new HttpPost(login_url2); //建立一个Post请求，第一步的方法是Post方法嘛
                //禁止重定向，由于刚刚Post的状态值是重定向，所以我们要去禁止它，不然网页会乱飞。
                httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
                //设置头部信息（头部信息在刚刚的Httpwatch下面Headers标签会有，不过我感觉写多跟写少没多大区别，只是多写没有坏处吧。）
                httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

                List<NameValuePair> params = new ArrayList<NameValuePair>();
//                params.add(new BasicNameValuePair("__VIEWSTATE", "dDwyODE2NTM0OTg7Oz4J1M0E12oUlEr84Lqk6/XAPSioRg=="));
////                params.add(new BasicNameValuePair("__VIEWSTATE", "/wEPDwUJNDcyMzA1MjkxZGRTx3lVi2lf6h+y/PVVH1qMZzouJg=="));
////                params.add(new BasicNameValuePair("__EVENTVALIDATION", "/wEWCwLkl9v4DwLs0bLrBgLs0fbZDAK/wuqQDgKAqenNDQLN7c0VAuaMg+INAveMotMNAoznisYGArursYYIAt+RzN8IIdJ+D2D5xaddz6rv7AABSyHhO14="));
//                params.add(new BasicNameValuePair("txtUserName", "1410421059"));// 账号
//                params.add(new BasicNameValuePair("TextBox2", "1996@0722"));// 密码
//                params.add(new BasicNameValuePair("txtSecretCode", ""));
//                params.add(new BasicNameValuePair("RadioButtonList1", "学生"));// 学生
//                params.add(new BasicNameValuePair("Button1", ""));
//                params.add(new BasicNameValuePair("lbLanguage", ""));
//                params.add(new BasicNameValuePair("hidPdrs", ""));
//                params.add(new BasicNameValuePair("hidsc", ""));

                params.add(new BasicNameValuePair("username", "18326143595"));
                params.add(new BasicNameValuePair("password", "1996@0722"));
                params.add(new BasicNameValuePair("lt", "LT-41834-jo39Lsk7NXfJaKabLUcEkQfOECezeG"));
                params.add(new BasicNameValuePair("execution", "e4s1"));
                params.add(new BasicNameValuePair("_eventId", "submit"));


                try {
                    // 传递参数的时候注意编码使用,否则乱码
                    httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
                    //响应请求
                    HttpResponse response = client.execute(httpPost);
                    //获取响应状态码
                    int Status = response.getStatusLine().getStatusCode();
                    //302表示重定向状态
//                    if (Status == 302 || Status == 301) {
                        //获取响应的cookie值
                        cookie = response.getFirstHeader("Set-Cookie").getValue();
                        location = response.getFirstHeader("Location").getValue();

//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Log.d("tb",cookie + "\n" + location);
*/
//                String  mainUrl = login_url + location;
                String mainUrl = "http://www.csdn.net/";

                HttpGet get = new HttpGet(mainUrl);
                //关键点,这里有个关键点就是设置头部信息中的Referer和cookie值，cookie值大家都知道，模拟登陆的时候必须带着cookie一起访问，但是Referer我无法理解，但必须要设置。
                //也就是必须指定它的Referer必须为当前访问的URL
//                get.setHeader("Referer", mainUrl);
//                get.addHeader("Cookie", "UserName=ThronBirds; UserInfo=3Q5gr9gij%2Flfx6OCL%2BkgRt8%2FhekUFbUnUpNdI9dXFbgyvagmtBv%2B2OBLpEc0bSJf1BznNdm1cGzGsAup%2FLoRSpcWn8ytBfoBcEaEpI%2FGWbM%3D; UserNick=ThronBirds; AU=C82; UN=ThronBirds; UE=\"\"; BT=1470364540891; access-token=5fdde1be-b9b0-42a6-b32b-536d79d8f6cc");

                try {
                    //获取Get响应，如果状态码是200的话表示连接成功
                    HttpResponse httpResponse = new DefaultHttpClient().execute(get);
                    Log.d("tb", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
//                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = httpResponse.getEntity();
                        //获取纯净的主页HTML源码，这里大家可以将mianhtml定义在其他地方
                        String mainhtml = EntityUtils.toString(entity);

                        Log.d("tb",mainhtml);

                        Message message = new Message();
                        message.what = 1;
                        message.obj = mainhtml;
                        handler.sendMessage(message);
//                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        };
        new Thread(runnable).start();


    }

}
